package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.byd.acegiext.domain.User;
import com.byd.acegiext.service.UserService;
import com.byd.acegiext.service.impl.UserServiceImpl;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicMaterialsDO;
import com.cssy.xxkj.basic.entity.BasicMaterialsTypeDO;
import com.cssy.xxkj.basic.entity.BasicSeriesDO;
import com.cssy.xxkj.basic.entity.BasicStorageInfoTestDO;
import com.cssy.xxkj.basic.entity.BasicStorageInfoTypeTestDO;
import com.cssy.xxkj.basic.service.IBasicCompanyTestService;
import com.cssy.xxkj.basic.service.IBasicMaterialsService;
import com.cssy.xxkj.basic.service.IBasicMaterialsTypeService;
import com.cssy.xxkj.basic.service.IBasicSeriesService;
import com.cssy.xxkj.basic.service.IBasicStorageInfoTestService;
import com.cssy.xxkj.basic.service.IBasicStorageInfoTypeTestService;
import com.cssy.xxkj.logic.contants.BillTypeConstant;
import com.cssy.xxkj.logic.contants.Constants;
import com.cssy.xxkj.logic.entity.LogicExcelToStoreDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageinDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseDetailsDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseInventoryDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseOtherinDO;
import com.cssy.xxkj.logic.entity.LogicWarehouseOtheroutDO;
import com.cssy.xxkj.logic.entity.LogicWarehousePriceDO;
import com.cssy.xxkj.logic.service.ILogicExcelToStoreService;
import com.cssy.xxkj.logic.service.ILogicProductionStorageInService;
import com.cssy.xxkj.logic.service.ILogicProductionStorageOutService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareService;
import com.cssy.xxkj.logic.service.ILogicSalesService;
import com.cssy.xxkj.logic.service.ILogicWareHouseOtherInService;
import com.cssy.xxkj.logic.service.ILogicWareHouseOtherOutService;
import com.cssy.xxkj.logic.service.ILogicWarehouseDetailsService;
import com.cssy.xxkj.logic.service.ILogicWarehouseInventoryService;
import com.cssy.xxkj.logic.service.ILogicWarehousePriceService;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;


@Controller
@RequestMapping("/logic/config")
public class InstoreController {
	
	private static final String INSTORE="/xxkj/logic/upload/inStore";
	
	@Resource(name="basicMaterialsService")//物料
	private IBasicMaterialsService basicMaterialsService;
	
	//仓库管理Service
	@Resource(name = "basicStorageInfoTestService")
	private IBasicStorageInfoTestService basicStorageInfoTestService;
	
	@Resource(name = "basicCompanyTestService")// 客户 or 供应商
	private IBasicCompanyTestService basicCompanyTestService;
	
	@Resource(name="basicMaterialsTypeService")//物料类型
	private IBasicMaterialsTypeService basicmaterTypeService;
	
	@Resource(name = "basicSeriesService")//产品系列
	private IBasicSeriesService basicSeriesService;
	
	@Resource(name = "logicWarehousePriceService") //平均价
	private ILogicWarehousePriceService logicWarehousePriceService;

	@Resource(name = "logicExcelToStoreService") //插入平均价
	private ILogicExcelToStoreService logicExcelToStoreService;
	
	@Resource(name = "logicWarehouseInventoryService")
	private ILogicWarehouseInventoryService logicWarehouseInventoryService;
	
	@Resource(name="logicSalesService") //销售
	private ILogicSalesService logicSalesService;
	
	@Resource(name="logicWareHouseOtherInService")//其他入库
	private ILogicWareHouseOtherInService logicWareHouseOtherInService;
	
	@Resource(name = "logicPurchaseWareService")//采购入库
	private ILogicPurchaseWareService logicPurchaseWareService;
	
	//仓库Service 
	@Resource(name = "basicStorageInfoTypeTestService")
	private IBasicStorageInfoTypeTestService basicStorageInfoTypeTestService;
	
	@Resource(name="logicWarehouseDetailsService")
	private ILogicWarehouseDetailsService logicWarehouseDetailsService;
	
	@Resource(name="logicProductionStorageInService")
	private ILogicProductionStorageInService logicProductionStorageInService;
	
	@Resource(name="logicWareHouseOtherOutService")//其他出库
	private ILogicWareHouseOtherOutService logicWareHouseOtherOutService;
	
	@Resource(name = "logicProductionStorageOutService")//成品出库
	private ILogicProductionStorageOutService logicProductionStorageOutService;
	
	@Resource(name="oftenMapUtil")
	private OftenMapUtil oftenMap;
	
	@RequestMapping("/toStore")
	public String toStore(HttpServletRequest request, HttpServletResponse response){
		return INSTORE;
	}
	@RequestMapping("/inEndProduct")
	public void inEndProduct(HttpServletRequest request, HttpServletResponse response){
		MultipartHttpServletRequest mRquest=(MultipartHttpServletRequest) request;
		MultipartFile file= mRquest.getFile("initExcel");
		SearchConditions scs= new SearchConditions();
		scs.clearCondition();
		scs.setLimitClause(null);
		Map<String , BasicStorageInfoTestDO> stroageInfoMap= oftenMap.getStroageInfoMap(scs);
		if(stroageInfoMap==null){
			throw new SyBaseException("仓库查询错误");
		}
		BasicStorageInfoTestDO storageInfo=stroageInfoMap.get("床品仓");
		Map<String , BasicMaterialsDO> materialMap=oftenMap.getMaterialMapByCode(scs); //物品
		Map<String , BasicMaterialsDO> materialByNameMap=oftenMap.getMaterialMapByName(scs); //物品
		Map<String , BasicCompanyTestDO> curMap=oftenMap.getCurMap(scs);//用户 or 供应商
		Map<String , BasicMaterialsTypeDO> materialTypeMap=oftenMap.getMaterialType(scs);
		User user= SessionUtil.getUser(request);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
		String date="2014-12-12-08-59-12";
		try {
			HSSFWorkbook excelStream= new HSSFWorkbook(file.getInputStream());
			HSSFSheet sheet= excelStream.getSheetAt(0);
			for(int i=1;i<=sheet.getLastRowNum();i++){
				HSSFRow row=sheet.getRow(i);
				if(row==null){
					continue;
				}
				String materialCode=this.getStringCellValue(row.getCell(0));
				if(StringUtils.isEmpty(materialCode)){
					throw new SyBaseException("第"+i+"条数据的数据编码为空");
				}
				String materialName=this.getStringCellValue(row.getCell(1));
				if(StringUtils.isEmpty(materialName)){
					throw new SyBaseException("第"+i+"条数据的数据名称为空");
				}
				String pocName=this.getStringCellValue(row.getCell(2));
				if(StringUtils.isEmpty(pocName)){
					throw new SyBaseException("第"+i+"条数据的数据业务员名称为空");	
				}
				String comName=this.getStringCellValue(row.getCell(3));
				if(StringUtils.isEmpty(comName)){
					throw new SyBaseException("第"+i+"条数据的数据客户名称为空");
				}
				String customerName=comName+"-"+pocName;
				String piAndSpec=this.getStringCellValue(row.getCell(4));
				if(StringUtils.isEmpty(piAndSpec)){
					throw new SyBaseException("第"+i+"条数据的数据单位名称为空");
				}
				String[] arr=piAndSpec.split("_");
				String materialPiCode=null;
				String materialSpec=null;
				materialPiCode=arr[0];
				if(arr.length>1){
					materialSpec=arr[(arr.length-1)];
				}
				String materialModel=this.getStringCellValue(row.getCell(5));
				if(StringUtils.isEmpty(materialModel)){
					throw new SyBaseException("第"+i+"条数据的数据规格型号为空");
				}
				String materialType=this.getStringCellValue(row.getCell(6));
				if(StringUtils.isEmpty(materialType)){
					throw new SyBaseException("第"+i+"条数据的数据类别为空");
				}
				String materialNum=this.getStringCellValue(row.getCell(8));
				if(StringUtils.isEmpty(materialNum)){
					throw new SyBaseException("第"+i+"条数据的数据库存数量为空");
				}
				String endNum=this.getStringCellValue(row.getCell(9));
				if(StringUtils.isEmpty(endNum)){
					throw new SyBaseException("第"+i+"条数据的数据期末数量为空");
				}
				LogicExcelToStoreDO excel= new LogicExcelToStoreDO();
				LogicWarehouseInventoryDO inventory= new LogicWarehouseInventoryDO();
				excel.setId(IDCodeTypeUtil.getId());
				inventory.setId(IDCodeTypeUtil.getId());
				BasicMaterialsDO material=materialMap.get(materialCode);//此类物品取编码看是否存在
				
				BasicMaterialsTypeDO materialTypeInfo=materialTypeMap.get(materialType);
				BasicCompanyTestDO cur=curMap.get(customerName);
				excel.setZd001MaterialCode(materialCode);
				excel.setZd001MaterialID(materialCode);
				excel.setZd001MaterialName(materialName);
				inventory.setZd003MaterialsId(materialCode);
				inventory.setZd004MaterialsCode(materialCode);
				inventory.setZd005MaterialsName(materialName);
				excel.setZd002MaterialModel(materialModel);
				inventory.setZd007MaterialsModel(materialModel);
				excel.setZd003MaterialSpec(materialSpec);
				inventory.setZd006MaterialsSpec(materialSpec);
				excel.setZd004MaterialTypeName(materialType);
				if(materialTypeInfo!=null){
					excel.setZd004MaterialTypeID(materialTypeInfo.getId());
					excel.setZd004MaterialTypeCode(materialTypeInfo.getZd001Code());
				}
				if(material==null){
					material=materialByNameMap.get(materialName);
					if(material==null){
						System.out.println("第"+i+"条编码为"+materialCode+"，名称为"+materialName+"有误");
						excel.setZd005MaterialUtil(null);
						inventory.setZd008Unit(null);
					}else{
						excel.setZd005MaterialUtil(material.getZd007Unit());
						inventory.setZd008Unit(material.getZd007Unit());
					}
				}
				excel.setZd009MaterialOutStoreNumber(new BigDecimal(endNum));
				inventory.setZd009Quantity(new BigDecimal(materialNum));
				excel.setZd011ConsumerName(customerName);
				inventory.setZd028CustomerName(customerName);
				if(cur!=null){
					excel.setZd011ConsumerID(cur.getId());
					inventory.setZd028CustomerID(cur.getId());
					excel.setZd011ConsumerCode(cur.getZd001Code());
					inventory.setZd028CustomerCode(cur.getZd001Code());
				}
				excel.setZd012WareHouseId(storageInfo.getId());
				excel.setZd012WareHouseCode(storageInfo.getZd002Code());
				excel.setZd012WareHouseName(storageInfo.getZd003Name());
				inventory.setZd001WhId(storageInfo.getId());
				inventory.setZd001WhCode(storageInfo.getZd002Code());
				inventory.setZd001WhName(storageInfo.getZd003Name());
				excel.setZd013MaterialSeries(" 床品系列 ");
				excel.setZd014MaterialPICode(materialPiCode);
				inventory.setZd026PiCode(materialPiCode);
				System.out.println("第"+i+"条数据无误");
				excel.setZd016Remark("在库存表面的设置他的录入时间是2014-12-12-08-59-12保证出入库循序");
				this.logicExcelToStoreService.saveLogicExcelToStoreDO(excel, user);
				inventory.setBizCreatorDate(sdf.parse(date));
				inventory.setBizCreatorName(user.getName());
				inventory.setBizVersion(1);
				inventory.setBizVersionMark(1);
				this.logicWarehouseInventoryService.save(inventory, user);
		}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	@RequestMapping("/inRunNum")
	public void inRunNum(HttpServletRequest request, HttpServletResponse response) {
		SearchConditions scs= new SearchConditions();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("initExcel");
		List<LogicWarehouseOtheroutDO> otherOutList= this.logicWareHouseOtherOutService.findListByExample(scs).getResults();
		Map<String, LogicWarehouseOtheroutDO> otherOutMap=new HashMap<String, LogicWarehouseOtheroutDO>();
		User user=SessionUtil.getUser(multipartRequest);
		int a=100;
		for(LogicWarehouseOtheroutDO ld:otherOutList){
			if(ld.getZd013RunningNumber().equals("0142017")){
				ld.setZd013RunningNumber("");
				a= this.logicWareHouseOtherOutService.update(ld,user );
			}
			otherOutMap.put(ld.getZd001OutCode(), ld);
		}
		
		try {
			HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
			HSSFSheet sheet = wb.getSheetAt(0);
			for (int j = 1; j <= sheet.getLastRowNum(); j++) {
				HSSFRow row = sheet.getRow(j);
				if(row==null){
					continue;
				}
				String key=getStringCellValue(row.getCell(0)).trim();
				String value=getStringCellValue(row.getCell(1)).trim();
				LogicWarehouseOtheroutDO otherOut=otherOutMap.get(key);
				if(otherOut==null){
					throw new SyBaseException("出库单号为"+key+"发生错误");
				}
				otherOut.setZd013RunningNumber(value);
				this.logicWareHouseOtherOutService.update(otherOut, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
				
	}
	
	
	@RequestMapping("/inDetails")
	public void inDetails(HttpServletRequest request, HttpServletResponse response){
		String msg="";
		SearchConditions scsclean = new SearchConditions();
		//其他出库 对成品仓
		List<LogicWarehouseOtheroutDO> otherOutList= logicWareHouseOtherOutService.findListByExample(scsclean).getResults();
		Map<String, LogicWarehouseOtheroutDO> otherOutMap= new HashMap<String, LogicWarehouseOtheroutDO>();
		for(LogicWarehouseOtheroutDO psd:otherOutList){
			otherOutMap.put(psd.getZd001OutCode(), psd);
		}
		//成品出库
		List<LogicProductionStorageoutDO> soOut= logicProductionStorageOutService.findListByExample(scsclean).getResults();
		Map<String, LogicProductionStorageoutDO> storageOutMap= new HashMap<String, LogicProductionStorageoutDO>();
		for(LogicProductionStorageoutDO sd:soOut){
			storageOutMap.put(sd.getZd001OutCode(), sd);
		}
		//查询所有的其他入库单
		List<LogicWarehouseOtherinDO> otherInList=logicWareHouseOtherInService.findListByExample(scsclean).getResults();
		Map<String, LogicWarehouseOtherinDO> otherInMap= new HashMap<String, LogicWarehouseOtherinDO>();
		for(LogicWarehouseOtherinDO oi:otherInList){
			otherInMap.put(oi.getZd001InCode(), oi);
		}
		//采购入库
		List<LogicPurchaseWareDO> purchaseList=logicPurchaseWareService.findListByExample(scsclean).getResults();
		Map<String, LogicPurchaseWareDO> purchaseMap=new HashMap<String, LogicPurchaseWareDO>();
		for(LogicPurchaseWareDO ld:purchaseList){
			purchaseMap.put(ld.getZd003Code(), ld);
		}
		//成品入库
		List<LogicProductionStorageinDO> strotageList=logicProductionStorageInService.findListByExample(scsclean).getResults();
		Map<String, LogicProductionStorageinDO> strotageMap= new HashMap<String, LogicProductionStorageinDO>();
		for(LogicProductionStorageinDO pd:strotageList){
			strotageMap.put(pd.getZd001InCode(), pd);
		}
		//仓库类型
		List<BasicStorageInfoTypeTestDO> storageTypeList=basicStorageInfoTypeTestService.findListByExample(scsclean).getResults();
		Map<String, String> storageTypeMap=new HashMap<String, String>();
		for(BasicStorageInfoTypeTestDO bd:storageTypeList){
			storageTypeMap.put(bd.getId(), bd.getZd001Code());//为成品时  value=成品
		}
		//获得仓库的map
		Map<String , Boolean> isProSto= new HashMap<String, Boolean>();
		List<BasicStorageInfoTestDO> whList=basicStorageInfoTestService.findListByExample(scsclean).getResults();
		for(BasicStorageInfoTestDO wh:whList){
			String stm=storageTypeMap.get(wh.getZd001WhTypeId());
			if(StringUtils.isNotEmpty(stm)&&stm.equals("WHLX1411170001")){
				isProSto.put(wh.getId(), true);
			}else{
				isProSto.put(wh.getId(), false);
			}
		}
		//客户或者供应商的Map
		Map<String , BasicCompanyTestDO> curMap=new HashMap<String, BasicCompanyTestDO>();
		List<BasicCompanyTestDO> lbc = basicCompanyTestService.findListByExample(scsclean).getResults();
		for(BasicCompanyTestDO lt:lbc){
			curMap.put(lt.getZd003ZhName(), lt);
		}
		SearchResult result= logicWarehouseDetailsService.findListByExample(scsclean);
		List<LogicWarehouseDetailsDO> ld=result.getResults();
		for(LogicWarehouseDetailsDO lwd:ld){
			if(lwd.getZd002BillType().equals(BillTypeConstant.PURCHASEWARE)){
    			//lwd.setZd002BillType("采购入库");
    			LogicPurchaseWareDO pwd=purchaseMap.get(lwd.getZd001BillCode());
    			if(pwd==null){
    				msg=msg+ "采购入库"+lwd.getZd001BillCode()+",ID为"+lwd.getId()+",有误(查找不到)。";
    				continue;
    			}
    			//判断仓库类型
    			if(isProSto.get(lwd.getZd003WhId())){//成品仓 取客户
    				BasicCompanyTestDO bct=curMap.get(pwd.getZd019AccountName());
    				if(bct!=null){
    					lwd.setZd022ConsumerName(bct.getZd003ZhName());
        				lwd.setZd022ConsumerCode(bct.getZd001Code());
        				lwd.setZd022ConsumerID(bct.getId());
    				}else{
    					lwd.setZd022ConsumerName(pwd.getZd019AccountName());
    				}
    			}else{//不是成品仓  取供应商
    				lwd.setZd022ConsumerName(pwd.getZd008SupeName());
    				lwd.setZd022ConsumerCode(pwd.getZd008SupeCode());
    				lwd.setZd022ConsumerID(pwd.getZd008SupeId());
    			}
    			
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.PURCHASERETURN)){
    			//lwd.setZd002BillType("采购退货");
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.ALLOCATION)){
    			//lwd.setZd002BillType("调拨");
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.OTHEROUTWH)){
    			//lwd.setZd002BillType("其他出库");
    			LogicWarehouseOtheroutDO otherOut=otherOutMap.get(lwd.getZd001BillCode());
    			if(isProSto.get(lwd.getZd003WhId())){//判断是否是成品仓
    				if(otherOut==null){
    					msg=msg+ "其他出库"+lwd.getZd001BillCode()+",ID为"+lwd.getId()+",有误(查找不到)。";
    					continue;
    				}
    				BasicCompanyTestDO bct=curMap.get(otherOut.getZd011CustomerName());//客户
    				if(bct!=null){
    					lwd.setZd022ConsumerName(bct.getZd003ZhName());
        				lwd.setZd022ConsumerCode(bct.getZd001Code());
        				lwd.setZd022ConsumerID(bct.getId());
    				}else{
    					lwd.setZd022ConsumerName(otherOut.getZd011CustomerName());
    					lwd.setZd022ConsumerCode(otherOut.getZd011CustomerCode());
    					lwd.setZd022ConsumerID(otherOut.getZd011CustomerID());
    				}
    			}
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.OTHERINWH)){
    			//lwd.setZd002BillType("其他入库");
    			LogicWarehouseOtherinDO pwd=otherInMap.get(lwd.getZd001BillCode());
    			if(pwd==null){
    				msg=msg+ "其他入库"+lwd.getZd001BillCode()+",ID为"+lwd.getId()+",有误(查找不到)。";
    				continue;
    			}
    			//判断入库仓库类型
    			if(isProSto.get(lwd.getZd003WhId())){//成品仓 取客户
    				BasicCompanyTestDO bct=curMap.get(pwd.getZd013AccountName());//客户或者供应商
    				if(bct!=null){
    					lwd.setZd022ConsumerName(bct.getZd003ZhName());
        				lwd.setZd022ConsumerCode(bct.getZd001Code());
        				lwd.setZd022ConsumerID(bct.getId());
    				}else{
    					lwd.setZd022ConsumerName(pwd.getZd013AccountName());
    				}
    			}else{//不是成品仓 去供应商
    				lwd.setZd022ConsumerName(pwd.getZd011CustomerName());
    				lwd.setZd022ConsumerCode(pwd.getZd011CustomerCode());
    				lwd.setZd022ConsumerID(pwd.getZd011CustomerID());
    			}
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.PROIN)){
    			//lwd.setZd002BillType("成品入库");
    			LogicProductionStorageinDO psd= strotageMap.get(lwd.getZd001BillCode());
    			if(psd==null){
    				msg= msg+"成品入库"+lwd.getZd001BillCode()+",ID为"+lwd.getId()+",有误(查找不到)。";
    				continue;
    			}
    			BasicCompanyTestDO bct=curMap.get(psd.getZd012CustomerName());//客户
				if(bct!=null){
					lwd.setZd022ConsumerName(bct.getZd003ZhName());
    				lwd.setZd022ConsumerCode(bct.getZd001Code());
    				lwd.setZd022ConsumerID(bct.getId());
				}else{
					lwd.setZd022ConsumerName(psd.getZd012CustomerName());
					lwd.setZd022ConsumerCode(psd.getZd012CustomerCode());
					lwd.setZd022ConsumerID(psd.getZd012CustomerId());
				}
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.PROOUT)){
    			//lwd.setZd002BillType("销售出库");
    			LogicProductionStorageoutDO storageOutDo=storageOutMap.get(lwd.getZd001BillCode());
    			if(storageOutDo==null){
    				msg= msg+"销售出库"+lwd.getZd001BillCode()+",ID为"+lwd.getId()+",有误(查找不到)。";
    				continue;
    			}
    			//销售出库一定会有客户
    			lwd.setZd022ConsumerName(storageOutDo.getZd012CustomerName());
				lwd.setZd022ConsumerCode(storageOutDo.getZd012CustomerCode());
				lwd.setZd022ConsumerID(storageOutDo.getZd012CustomerId());
    			
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.MATERIALOUT)){
    			//lwd.setZd002BillType("生产领料出库");
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.PRORETURN)){
    			//lwd.setZd002BillType("生产退料");
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.CHECKBACK)){
    			//lwd.setZd002BillType("反审");
    		}else if(lwd.getZd002BillType().equals(BillTypeConstant.CHECKTASK)){
    			//lwd.setZd002BillType("盘点");
    		}
			logicWarehouseDetailsService.update(lwd, SessionUtil.getUser(request));
			System.out.println(msg);
		}
		
	}
	
	
	@RequestMapping("/instore")
	@ResponseBody
	public Map<String, Object> instore(HttpServletRequest request, HttpServletResponse response){
		SearchConditions scs= new SearchConditions();
		BodyMsg bodyMap = BodyMsg.getInstance();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("initExcel");
		//获得物料信息
		Map<String , BasicMaterialsDO> materialMap= new HashMap<String , BasicMaterialsDO>();
		scs.clearCondition();
		List<BasicMaterialsDO> materList = basicMaterialsService.findListByExample(scs).getResults();
		for(BasicMaterialsDO mater:materList){
			if(mater.getId()==null){
				continue;
			}
			String key=mater.getZd001Code()+"_"+mater.getZd002Name()+"_"//编码 名称
					+mater.getZd003Spec()+"_"+mater.getZd004Model()+"_"//规格  型号
					+mater.getZd033Color()+"_"+mater.getZd034Quality();// 颜色  材质
			materialMap.put(key, mater);
		}
		//获得仓库的map
		Map<String , BasicStorageInfoTestDO> wareHouseMap= new HashMap<String, BasicStorageInfoTestDO>();
		scs.clearCondition();
		List<BasicStorageInfoTestDO> whList=basicStorageInfoTestService.findListByExample(scs).getResults();
		for(BasicStorageInfoTestDO wh:whList){
			wareHouseMap.put(wh.getZd003Name(), wh);
		}
		//客户或者供应商的Map
		Map<String , BasicCompanyTestDO> curMap=new HashMap<String, BasicCompanyTestDO>();
		scs.clearCondition();
		List<BasicCompanyTestDO> lbc = basicCompanyTestService.findListByExample(scs).getResults();
		for(BasicCompanyTestDO lt:lbc){
			curMap.put(lt.getZd003ZhName(), lt);
		}
		//物品类型
		Map<String , BasicMaterialsTypeDO> mtMap= new HashMap<String , BasicMaterialsTypeDO>();
		scs.clearCondition();
		List<BasicMaterialsTypeDO> mtlist= basicmaterTypeService.findListByExample(scs).getResults();
		for(BasicMaterialsTypeDO bd:mtlist){
			mtMap.put(bd.getZd002Name(), bd);
		}
		//物品系列
		Map<String , BasicSeriesDO> seriesMap= new HashMap<String , BasicSeriesDO>();
		scs.clearCondition();
		List<BasicSeriesDO> bsList= basicSeriesService.findListByExample(scs).getResults();
		for(BasicSeriesDO bsd:bsList){
			seriesMap.put(bsd.getZd002Name(), bsd);
		}
		//表 中的平均价
		Map<String , LogicWarehousePriceDO> priceExMap= new HashMap<String , LogicWarehousePriceDO>();
		scs.clearCondition();
		List<LogicWarehousePriceDO> lwp= logicWarehousePriceService.findListByExample(scs).getResults();
		for(LogicWarehousePriceDO lw:lwp){
			String pKey=lw.getZd001MaterialsCode()+"_"+lw.getZd001MaterialsName()+"_"+//编码 名称
					 	lw.getZd001MaterialsSpec()+"_"+lw.getZd001MaterialsModel()+"_"+//规格 型号
					 	lw.getZd001MaterialsColor()+"_"+lw.getZd001MaterialsQuanlity();// 颜色 材质 
			priceExMap.put(pKey, lw);
		}
		
		//现有库存
		Map<String, LogicWarehouseInventoryDO> whExMap= new HashMap<String, LogicWarehouseInventoryDO>();
		List<LogicWarehouseInventoryDO> wiList= logicWarehouseInventoryService.findListByExample(scs).getResults();
		for(LogicWarehouseInventoryDO wi:wiList){
			String wiKey= wi.getZd004MaterialsCode()+"_"+wi.getZd005MaterialsName()+"_"+// 编码  名称
						  wi.getZd006MaterialsSpec()+"_"+wi.getZd007MaterialsModel()+"_"+//规格  型号	
						  wi.getZd008MaterialsColor()+"_"+wi.getZd008MaterialsQuanlity()// 颜色  材质
						  +"_"+wi.getZd028CustomerName()+"_"+wi.getZd026PiCode()+"_"+
						  wi.getZd001WhCode()+"_"+wi.getZd001WhName()+"_"+wi.getZd028CustomerName();//仓库编码 仓库名称 客户名
			whExMap.put(wiKey, wi);
		}
		Map<String, LogicWarehouseInventoryDO> whMap= new HashMap<String, LogicWarehouseInventoryDO>();
		//excel的平均价
		List<LogicExcelToStoreDO> listTS= new ArrayList<LogicExcelToStoreDO>();
		try {
			HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
			HSSFSheet sheet = wb.getSheetAt(0);
			int a=0;
			String msg="";
			for (int j = 1; j <= sheet.getLastRowNum(); j++) {
				LogicWarehouseInventoryDO gcIn= new LogicWarehouseInventoryDO();
				LogicExcelToStoreDO gcExcel= new LogicExcelToStoreDO();
				HSSFRow row = sheet.getRow(j);
				if (row == null) {
					continue;
				}
				String materialCode=getStringCellValue(row.getCell(0));//物品编号
				if(StringUtils.isEmpty(materialCode)){
					materialCode=null;
				}
				gcExcel.setZd001MaterialCode(materialCode);
				gcIn.setZd004MaterialsCode(materialCode);
				
				String materialName=getStringCellValue(row.getCell(1));//物品名称
				if(StringUtils.isEmpty(materialName)){
					materialName=null;
				}
				gcExcel.setZd001MaterialName(materialName);
				gcIn.setZd005MaterialsName(materialName);
				
				String materialModel=getStringCellValue(row.getCell(2));//物品型号
				if(StringUtils.isEmpty(materialModel)){
					materialModel=null;
				}
				gcExcel.setZd002MaterialModel(materialModel);
				gcIn.setZd007MaterialsModel(materialModel);
				
				String materialSpec=getStringCellValue(row.getCell(3));//物品规格
				if(StringUtils.isEmpty(materialSpec)){
					materialSpec=null;
				}
				gcExcel.setZd003MaterialSpec(materialSpec);
				gcIn.setZd006MaterialsSpec(materialSpec);
				String materialType=getStringCellValue(row.getCell(4));//物品类别
				BasicMaterialsTypeDO bd=new BasicMaterialsTypeDO();
				if(StringUtils.isEmpty(materialType)){
					materialType=null;
					bd=null;
				}else{
					bd=mtMap.get(materialType);
				}
				if(bd!=null&&bd.getId()!=null){
					gcExcel.setZd004MaterialTypeID(bd.getId());
					gcExcel.setZd004MaterialTypeCode(bd.getZd001Code());
				}
				gcExcel.setZd004MaterialTypeName(materialType); //把现有的类别当作材质存入库存中
				gcIn.setZd008MaterialsQuanlity(materialType);
				//lwi 暂缺
				String mKey=materialCode+"_"+materialName+"_"//编码 名称
						+materialSpec+"_"+materialModel+"_"//规格 型号
						+null+"_"+materialType;//颜色  材质
				BasicMaterialsDO bm = materialMap.get(mKey);
				if(bm==null){
					gcIn.setZd003MaterialsId(materialCode);
				}else{
					gcIn.setZd003MaterialsId(bm.getId());
				}
				
				
				String materialUtil=getStringCellValue(row.getCell(5));//物品单位
				gcExcel.setZd005MaterialUtil(materialUtil);
				gcIn.setZd008Unit(materialUtil);
				
				String materialPrice=getStringCellValue(row.getCell(6));//物品平均价
				BigDecimal price = BigDecimal.ZERO;
				if(materialPrice==null||materialPrice.equals("")||StringUtils.isEmpty(materialPrice)){
					price = BigDecimal.ZERO;
				}else{
					price = new BigDecimal(materialPrice);
				}
				gcExcel.setZd006MaterialPrice(price);

				
				String beginSize=getStringCellValue(row.getCell(7));//期初数量
				if(beginSize==null||beginSize.equals("")||StringUtils.isEmpty(beginSize)){
					beginSize="0";
				}
				gcExcel.setZd007MaterialBeginNumber(new BigDecimal(beginSize));
				
				String beginMoney=getStringCellValue(row.getCell(8));//期初金额
				if(beginMoney==null||beginMoney.equals("")||StringUtils.isEmpty(beginMoney)){
					beginMoney="0";
				}
				gcExcel.setZd007MaterialBeginMoney(new BigDecimal(beginMoney));
				
				String inStoreSize=getStringCellValue(row.getCell(9));//入库数量
				if(inStoreSize==null||inStoreSize.equals("")||StringUtils.isEmpty(inStoreSize)){
					inStoreSize="0";
				}
				gcExcel.setZd008MaterialInStoreNumber(new BigDecimal(inStoreSize));
				
				String inStoreMoney=getStringCellValue(row.getCell(10));//入库金额
				if(inStoreMoney==null||inStoreMoney.equals("")||StringUtils.isEmpty(inStoreMoney)){
					inStoreMoney="0";
				}
				gcExcel.setZd008MaterialInStoreMoney(new BigDecimal(inStoreMoney));
				
				String outStoreSize=getStringCellValue(row.getCell(11));//出库数量
				if(outStoreSize==null||outStoreSize.equals("")||StringUtils.isEmpty(outStoreSize)){
					outStoreSize="0";
				}
				gcExcel.setZd009MaterialOutStoreMoney(new BigDecimal(outStoreSize));
				
				String outStoreMoney=getStringCellValue(row.getCell(12));//出库金额
				if(outStoreMoney==null||outStoreMoney.equals("")||StringUtils.isEmpty(outStoreMoney)){
					outStoreMoney="0";
				}
				gcExcel.setZd009MaterialOutStoreMoney(new BigDecimal(outStoreMoney));
				
				String endSize=getStringCellValue(row.getCell(13));//期末数量
				BigDecimal endSum = BigDecimal.ZERO;
				if(endSize==null||endSize.equals("")||StringUtils.isEmpty(endSize)){
					endSum = BigDecimal.ZERO;
				}else{
					endSum = new BigDecimal(endSize);
				}
				gcExcel.setZd010MaterialEndNumber(endSum);
				gcIn.setZd009Quantity(endSum);
				
				//期末金额
				BigDecimal endSumMoney = price.multiply(endSum);
				gcExcel.setZd010MaterialEndMoney(endSumMoney);
				
				String customerName=getStringCellValue(row.getCell(15));//客户或者供应商名称   单位名称
				BasicCompanyTestDO bt=curMap.get(customerName);
				if(bt!=null){
					gcExcel.setZd011ConsumerCode(bt.getZd001Code());
					gcExcel.setZd011ConsumerID(bt.getId());
					gcIn.setZd028CustomerID(bt.getId());
					gcIn.setZd028CustomerCode(bt.getZd001Code());
				}
				gcIn.setZd028CustomerName(customerName);
				gcExcel.setZd011ConsumerName(customerName);
				String wareHouseName=getStringCellValue(row.getCell(16));//仓库名称
				if(StringUtils.isEmpty(wareHouseName)){
					wareHouseName=null;
				}
				gcExcel.setZd012WareHouseName(wareHouseName);
				gcIn.setZd001WhName(wareHouseName);
				
				String series=getStringCellValue(row.getCell(17));//系列
				gcExcel.setZd013MaterialSeries(series);
				
				
				String inStoreMonth=getStringCellValue(row.getCell(18));//入库月份
				gcExcel.setZd015InStoreMonth(inStoreMonth);
				
				String PICode=getStringCellValue(row.getCell(19));//PI号
				if(StringUtils.isEmpty(PICode)){
					PICode=null;
				}
				gcExcel.setZd014MaterialPICode(PICode);
				gcIn.setZd026PiCode(PICode);
				// 编码  名称 规格  型号	颜色 材质
				String whStr = materialCode+"_"+materialName+"_"
						+materialSpec+"_"+materialModel+"_"+
						null+"_"+materialType+"_"+PICode+"_"+wareHouseName;
				BasicStorageInfoTestDO bs= wareHouseMap.get(wareHouseName);
				if(bs!=null){
					gcExcel.setZd012WareHouseId(bs.getId());
					gcExcel.setZd012WareHouseCode(bs.getZd002Code());
					////仓库编码 仓库名称
					whStr = whStr+"_"+bs.getZd002Code()+"_"+bs.getZd003Name();
					gcIn.setZd001WhCode(bs.getZd002Code());
					gcIn.setZd001WhId(bs.getId());
					//品均价不区分仓库
				}else{
					whStr = whStr+"_"+null+"_"+null;
				}
				whStr=whStr+customerName;//可根据唯一条件 +仓库+客户
				String remark=getStringCellValue(row.getCell(20));//备注
				gcExcel.setZd016Remark(remark);
				gcIn.setZd027Decript(remark);
				//判断物料在数据库中是否存在平均价
				gcIn.setZd020Batch("BC");
				gcIn.setRemoved(0l);
				gcIn.setBizCreatorName(SessionUtil.getUser(request).getName());
				gcIn.setBizCreatorDate(new Date());
				gcIn.setBizModifyDate(new Date());
				gcIn.setBizModifyName(SessionUtil.getUser(request).getName());
				
				if(whMap.get(whStr)==null){
					whMap.put(whStr, gcIn);
				}else{
					LogicWarehouseInventoryDO exInventory = whMap.get(whStr);
					//在给的库存是的好存在  唯一条件加上PI好都是一样，但是又不是同一个物品
					exInventory.setZd009Quantity(endSum.add(exInventory.getZd009Quantity()));
					whMap.put(whStr, exInventory);
					a++;
					msg=msg+"\\n"+"第"+a+"次出现重复数据,仓库名称为："+exInventory.getZd001WhName()+"物品名称为："
							+exInventory.getZd005MaterialsName()+"型号为："+exInventory.getZd007MaterialsModel()+
							"规格类型为："+exInventory.getZd006MaterialsSpec()+"key是："+whStr;
				}
				listTS.add(gcExcel);
			}
			//插入平均价
			User user=SessionUtil.getUser(request);
			for(LogicExcelToStoreDO excelTo: listTS){
				logicExcelToStoreService.saveLogicExcelToStoreDO(excelTo, user);
			}
			//组装最新的库存
			for(String _whKeyStr:whMap.keySet()){
				LogicWarehouseInventoryDO gcwh= whMap.get(_whKeyStr);
				if(gcwh==null){
					continue;
				}
				whExMap.put(_whKeyStr, gcwh);
			}
			for(String _whKeyStr:whExMap.keySet()){
				LogicWarehouseInventoryDO wh= whExMap.get(_whKeyStr);
				if(wh==null){
					continue;
				}
				LogicWarehouseDetailsDO lw= new LogicWarehouseDetailsDO();
				lw.setZd002BillType("PD");
				lw.setZd003WhId(wh.getZd001WhId());
				lw.setZd003WhCode(wh.getZd001WhCode());
				lw.setZd003WhName(wh.getZd001WhName());
				lw.setZd004WhPositionId(null);
				lw.setZd004WhPositionCode(null);
				lw.setZd005MaterialsId(wh.getZd003MaterialsId());
				lw.setZd005MaterialsCode(wh.getZd004MaterialsCode());
				lw.setZd005MaterialsName(wh.getZd005MaterialsName());
				lw.setZd006MaterialsSpec(wh.getZd006MaterialsSpec());
				lw.setZd007MaterialsModel(wh.getZd007MaterialsModel());
				lw.setZd008MaterialsQuanlity(wh.getZd008MaterialsQuanlity());
				lw.setZd008MaterialsColor(wh.getZd008MaterialsColor());
				lw.setZd009BasicUnit(wh.getZd008Unit());
				lw.setZd011BasicQuantity(wh.getZd009Quantity());
				lw.setZd012Status(wh.getZd025Status());
				lw.setZd013Price(wh.getZd024Price());
				lw.setZd014StockPrice(null);
				lw.setZd019Batch(Constants.SYS_DEFAULT_BATCH);
				lw.setZd020PiCode(wh.getZd026PiCode());
				lw.setZd022ConsumerID(wh.getZd028CustomerID());
				lw.setZd022ConsumerCode(wh.getZd028CustomerCode());
				lw.setZd022ConsumerName(wh.getZd028CustomerName());
				lw.setBizCreatorName(wh.getBizCreatorName());
				lw.setBizCreatorDate(wh.getBizCreatorDate());
				logicWarehouseInventoryService.updateWhAffstockQuantity(lw, user,true);
				
			}
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			System.out.println(msg);
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}
	private String getStringCellValue(HSSFCell cell) {
		if(cell==null||"".equals(cell)){
			return "";
		}
		String strCell = "";
		switch (cell.getCellType()) {
			case HSSFCell.CELL_TYPE_STRING:
				strCell = cell.getStringCellValue();
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				strCell = String.valueOf(cell.getNumericCellValue());
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				strCell = String.valueOf(cell.getBooleanCellValue());
				break;
			case HSSFCell.CELL_TYPE_BLANK:
				strCell = "";
				break;
			default:
				strCell = "";
				break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
	/*	if (cell == null) { 
	 * 
			return "";
		}*/
		return strCell;
	}
	/**
	 * 对本月的所有入库数据重新入库
	 * @param request
	 * @param response
	 */
	@RequestMapping("/aginInStore")
	public void aginInStore( ){

		//查询生生产入库的记录
		SearchConditions inScs = new SearchConditions();
		inScs.addCondition("zd002BillType", "PI", SearchCondition.OP_EQUAL);
		List<LogicWarehouseDetailsDO> prodTailList=logicWarehouseDetailsService.findListByExample(inScs).getResults();
		for(LogicWarehouseDetailsDO prodTail : prodTailList){
			if(prodTail==null||StringUtils.isBlank(prodTail.getId())){
				continue;
			}
			String userName = prodTail.getBizCreatorName();
			UserService us = new UserServiceImpl();
			com.byd.acegiext.domain.User user= us.getUserByName(userName, "1");
			logicWarehouseInventoryService.updateWhAffstockQuantity(prodTail,user, true);
		}
		//查询采购入库
		inScs.clearCondition();
		inScs.addCondition("zd002BillType", "PSW", SearchCondition.OP_EQUAL);
		List<LogicWarehouseDetailsDO> pcswTailList=logicWarehouseDetailsService.findListByExample(inScs).getResults();
		for(LogicWarehouseDetailsDO pcswTail : pcswTailList){
			if(pcswTail==null||StringUtils.isBlank(pcswTail.getId())){
				continue;
			}
			String userName = pcswTail.getBizCreatorName();
			UserService us = new UserServiceImpl();
			com.byd.acegiext.domain.User user= us.getUserByName(userName, "1");
			logicWarehouseInventoryService.updateWhAffstockQuantity(pcswTail,user, true);
		}
		//查询其他入库
		inScs.clearCondition();
		inScs.addCondition("zd002BillType", "CK", SearchCondition.OP_EQUAL);
		List<LogicWarehouseDetailsDO> qtTailList=logicWarehouseDetailsService.findListByExample(inScs).getResults();
		for(LogicWarehouseDetailsDO qtTail : qtTailList){
			if(qtTail==null||StringUtils.isBlank(qtTail.getId())){
				continue;
			}
			String userName = qtTail.getBizCreatorName();
			UserService us = new UserServiceImpl();
			com.byd.acegiext.domain.User user= us.getUserByName(userName, "1");
			logicWarehouseInventoryService.updateWhAffstockQuantity(qtTail,user, true);
		}

}
	
}
